import { ScrollView, View } from "@tarojs/components"
import React, { useCallback, useEffect, useRef, useState } from "react"
import { AtLoadMore } from "taro-ui"
import Taro, { useDidShow } from "@tarojs/taro"
import "./index.scss"
import OrderItem from "./components/orderItem"
import HistoryItem from "./components/historyItem"
import http from "../../utils/http"
import { debounce } from "../../utils"
import Empty from "../../components/empty"
import Modal from "../../components/Modal"

const historyTabList = [
  {
    label: "已完成",
    value: 4,
  },
  {
    label: "已取消",
    value: 5,
  },
]

export default function () {
  const [tabCurrent, setTabCurrent] = useState(0)
  const [historyTabCurrent, setHistoryTabCurrent] = useState(historyTabList[0].value)
  const [orderList, setOrderList] = useState([])
  const [status, setStatus] = useState("more")
  const [showModal, setShowModal] = useState(false)
  const [modalItem, setModalItem] = useState(null)
  const [refresherTriggeredStatus, setRefresherTriggeredStatus] = useState(false)
  const isFirstLoadRef = useRef(true)
  const pageDataRef = useRef({
    pageSize: 20,
    pageNum: 0,
  })

  const getOrderList = useCallback(
    debounce(async page => {
      if (status === "loading") return
      if (page.pageNum === 1) {
        setOrderList([])
      }
      setStatus("loading")
      const { data } = await http.post("/core/ticket/search/page/list", {
        ...page,
      })
      if (data) {
        let newList = [...orderList]
        if (page.pageNum === 1) {
          newList = data.records || []
        } else {
          data.records.forEach(item => {
            newList.push(item)
          })
        }
        setOrderList(newList)
        pageDataRef.current = {
          pageNum: data.current,
          pageSize: data.size,
        }
        setRefresherTriggeredStatus(false)

        if (data.total > newList.length) {
          setStatus("more")
        } else {
          setStatus("noMore")
        }
      } else setStatus("noMore")
    }, 200),
    [orderList]
  )

  const onScrollLoad = () => {
    if (status === "loading" || status === "noMore") return
    getOrderList({
      pageSize: pageDataRef.current.pageSize,
      pageNum: pageDataRef.current.pageNum + 1,
      ...getParams(),
    })
  }

  const getParams = () => {
    const params = {}
    if (tabCurrent == 0) {
      params.status = [0, 1, 2, 3]
    } else if (tabCurrent == 1 && historyTabCurrent !== null) {
      params.status = [historyTabCurrent]
    }
    return params
  }

  const onClickOrderItemButton = async item => {
    if (item.status == 1) {
      Taro.showToast({
        title: "线上支付功能暂未开通，请联系场馆线下支付",
        icon: "none",
      })
      // const { data } = await http.post("/core/pay/createPayOrder", { ticketId: item.ticketId })
      // console.log(data)
      // if (data) {
      // Taro.requestPayment({
      //   timeStamp: "",
      //   nonceStr: "",
      //   package: data.prepay_id,
      //   paySign: "",
      //   success: async () => {
      //     await http.post("/core/ticket/update", {
      //       ticketId: item.ticketId,
      //       status: "2",
      //     })
      // },
      //   fail: () => {
      //     Taro.showToast({
      //       title: "支付失败",
      //       icon: "none",
      //     })
      //   },
      // })
      // }
    } else if (item.status == 3) {
      setShowModal("take")
      setModalItem(item)
    }
  }

  useEffect(() => {
    const params = {
      pageSize: pageDataRef.current.pageSize,
      pageNum: 1,
    }
    getOrderList({
      ...params,
      ...getParams(),
    })
  }, [historyTabCurrent, tabCurrent])

  useDidShow(() => {
    if (isFirstLoadRef.current) {
      isFirstLoadRef.current = false
      const params = Taro.getCurrentInstance().router.params
      params.tabCurrent && setTabCurrent(params.tabCurrent)
    } else {
      const params = {
        pageSize: pageDataRef.current.pageSize,
        pageNum: 1,
      }
      getOrderList({
        ...params,
        ...getParams(),
      })
    }
  })

  const changeStatus = async s => {
    await http.post("/core/ticket/update", {
      ticketId: modalItem.ticketId,
      status: s,
    })
    const { data } = await http.get(`/core/ticket/search/${modalItem.ticketId}`)
    if (data) {
      if (tabCurrent !== 1) {
        setTabCurrent(1)
      } else {
        const findIndex = orderList.findIndex(i => i.ticketId == modalItem.ticketId)
        orderList[findIndex] = data
        setOrderList([...orderList])
      }
      setShowModal(false)
      Taro.showToast({
        title: "确认取拍成功",
        icon: "none",
      })
    } else {
      Taro.showToast({
        title: "确认取拍失败",
        icon: "none",
      })
    }
  }

  const modalData = {
    take: {
      title: "确认取拍",
      text: "请在收到球拍后，验收相关物品，无误后点击确认取拍",
      text2: "",
      confirmText: "确认取拍",
      onConfirm: () => {
        changeStatus(4)
      },
    },
  }

  return (
    <View className="page-order">
      <View className="tab">
        <View
          className={`tab-item ${tabCurrent == 0 ? "active" : ""}`}
          onClick={() => {
            tabCurrent !== 0 && setTabCurrent(0)
          }}
        >
          预约单
        </View>
        <View
          className={`tab-item ${tabCurrent == 1 ? "active" : ""}`}
          onClick={() => {
            tabCurrent !== 1 && setTabCurrent(1)
          }}
        >
          历史订单
        </View>
      </View>
      {tabCurrent == 1 && (
        <View className="history-tab">
          {historyTabList.map(item => {
            return (
              <View
                key={item.value}
                className={`history-tab-item ${historyTabCurrent == item.value ? "active" : ""}`}
                onClick={() => {
                  historyTabCurrent !== item.value && setHistoryTabCurrent(item.value)
                }}
              >
                {item.label}
              </View>
            )
          })}
        </View>
      )}
      <ScrollView
        className="order-scroll"
        refresherTriggered={refresherTriggeredStatus}
        onRefresherRefresh={() => {
          setRefresherTriggeredStatus(true)
          const params = {
            pageSize: pageDataRef.current.pageSize,
            pageNum: 1,
          }
          getOrderList({
            ...params,
            ...getParams(),
          })
        }}
        refresherEnabled
        refresherBackground="none"
        onScrollToLower={onScrollLoad}
        upperThreshold={50}
        scrollY
        style={{ top: tabCurrent == 0 ? "100rpx" : "200rpx" }}
      >
        {tabCurrent == 0 && (
          <View className="order-list">
            {orderList?.map(item => {
              return (
                <OrderItem
                  key={item.ticketId}
                  itemData={item}
                  onClickButton={() => onClickOrderItemButton(item)}
                ></OrderItem>
              )
            })}
          </View>
        )}
        {tabCurrent == 1 && (
          <View className="history-list">
            {orderList?.map(item => {
              return <HistoryItem key={item.ticketId} itemData={item}></HistoryItem>
            })}
          </View>
        )}
        {status === "loading" && (
          <View style={{ position: "relative", height: "100rpx" }}>
            <AtLoadMore status={status}></AtLoadMore>
          </View>
        )}
        {status === "noMore" && orderList?.length === 0 && <Empty></Empty>}
      </ScrollView>
      <Modal
        isOpened={showModal}
        titleText={modalData[showModal]?.title}
        cancelText="取消"
        onCancel={() => setShowModal(false)}
        onConfirm={() => modalData[showModal]?.onConfirm()}
        confirmText={modalData[showModal]?.confirmText}
      >
        <View className="modal-text">
          <View>{modalData[showModal]?.text}</View>
          <View>{modalData[showModal]?.text2}</View>
        </View>
      </Modal>
    </View>
  )
}
